package com.zHan.service.impl;

import com.zHan.exception.BaseException;
import com.zHan.mapper.CategoryMapper;
import com.zHan.pojo.Category;
import com.zHan.pojo.Result;
import com.zHan.service.CategoryService;
import com.zHan.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * ClassName: CategoryServiceImpl
 * Description:
 * date: 2023/11/9 0009 15:56
 *
 * @author zHan
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增文章分类
     *
     * @param category
     * @return
     */
    @Override
    public Result add(Category category) {
        // 补全参数
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        // 获取用户id
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        category.setCreateUser(userId);
        // 新增
        categoryMapper.insert(category);
        return Result.success("文章分类添加成功");
    }

    /**
     * 文章分类列表
     *
     * @return
     */
    @Override
    public Result list() {
        // 获取用户id
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        List<Category> categoryList = categoryMapper.list(userId);
        return Result.success(categoryList);

    }

    /**
     * 根据id查询分类
     *
     * @param id
     * @return
     */
    @Override
    public Result findById(Integer id) {
        // 查询
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new BaseException("查询失败，数据不存在");
        }
        return Result.success(category);
    }

    /**
     * 更新文章分类
     *
     * @param category
     * @return
     */
    @Override
    public Result update(Category category) {
        categoryMapper.update(category);
        return Result.success("文章分类更新成功");
    }

    /**
     * 删除文章分类
     *
     * @param id
     * @return
     */
    @Override
    public Result delete(Integer id) {
        categoryMapper.delete(id);
        return Result.success("文章分类删除成功");
    }
}
